package com.lhj.security.config.filter;

import com.lhj.security.config.security.UserAuthDetail;
import com.lhj.security.config.security.service.TokenService;
import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * @Description
 * @Author lhj
 * @Date 2024/12/26 16:53
 */
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {
    
    @Resource
    private TokenService tokenService;
    
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        UserAuthDetail userAuthDetail = tokenService.getLoginUser(request);
        if (userAuthDetail != null && SecurityContextHolder.getContext().getAuthentication() == null) {
            tokenService.verifyToken(userAuthDetail);
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userAuthDetail, null, userAuthDetail.getAuthorities());
            authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }
        doFilter(request, response, filterChain);
    }
}
